﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace com.haoest.QrPortal
{
    public sealed partial class ConnectedDevicesList : UserControl
    {
        private ConnectedDevicesList()
        {
            InitializeComponent();
            checkedListBox_ConnectedDevices.DataSource = null;
            checkedListBox_ConnectedDevices.DisplayMember = "name";
            checkedListBox_ConnectedDevices.ValueMember = "id";
            this.Dock = DockStyle.Fill;
        }

        public static readonly ConnectedDevicesList Instance = new ConnectedDevicesList();

        public void RefreshConnectedDevicesCheckedListBox(Object sender, Device.DeviceEventArgs e)
        {
            checkedListBox_ConnectedDevices.DataSource = Device.devices.GetDataTable();
            checkedListBox_ConnectedDevices.DisplayMember = "name";
            checkedListBox_ConnectedDevices.ValueMember = "id";
        }

        private void checkedListBox_ConnectedDevices_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)//判断是否右键点击
            {
                Point p = e.Location;//获取点击的位置
                int index = checkedListBox_ConnectedDevices.IndexFromPoint(p);  //根据位置获取右键点击项的索引
                checkedListBox_ConnectedDevices.SelectedIndex = index;  //设置该索引值对应的项为选定状态
            }
            if (e.Button == MouseButtons.Left)
            {
                Point p = e.Location;//获取点击的位置
                int index = checkedListBox_ConnectedDevices.IndexFromPoint(p);  //根据位置获取右键点击项的索引
                checkedListBox_ConnectedDevices.SelectedIndex = index;  //设置该索引值对应的项为选定状态
            }
        }



        private void contextMenuStrip_ConnectedDevices_Opening(object sender, CancelEventArgs e)
        {
            // 如果没有选择项，则不弹出右键菜单
            if (checkedListBox_ConnectedDevices.SelectedItem == null)
            {
                e.Cancel = true;
            }
        }

        private void 断开连接ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string deviceId = checkedListBox_ConnectedDevices.SelectedValue.ToString();
            Command.Disconnect(deviceId);
        }

        private void 设备重命名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RenameDialog rd = new RenameDialog();
            if (rd.ShowDialog() == DialogResult.OK)
            {
                string deviceId = checkedListBox_ConnectedDevices.SelectedValue.ToString();
                string deviceName = rd.NewName;
                Command.RenameDevice(deviceId, deviceName);
            }
        }
    }
}
